#include "CServer.h"

CServer::CServer(boost::asio::io_context& ioc, short port):_ioc(ioc),_port(port),_acceptor(ioc,boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))
{
	std::cout << "Server start" << std::endl;
	StartAccept();
}

void CServer::ClearSession(std::string uuid)
{
	std::lock_guard<std::mutex> lock(_mtx);
	_sessions.erase(uuid);
}

CServer::~CServer()
{
	std::cout << "~CServer()" << std::endl;
}

void CServer::HandleAccept(std::shared_ptr<CSession> new_session,const boost::system::error_code& ec)
{
	if (!ec) {
		new_session->start();
		std::lock_guard<std::mutex> lock(_mtx);
		_sessions.insert(std::make_pair(new_session->getuuid(), new_session));
	}
	else {
		std::cout << "Accept Failed:" << ec.what() << std::endl;
	}
	StartAccept();
}

void CServer::StartAccept()
{
	auto& ioc = IOServicePool::GetInst().getIOC();
	std::shared_ptr<CSession> new_session =  std::make_shared<CSession>(ioc, this);
	_acceptor.async_accept(new_session->getSocket(), std::bind(&CServer::HandleAccept, this, new_session, std::placeholders::_1));
}
